package com.zhu.salesmanagement;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.Overlay;
import com.baidu.mapapi.OverlayItem;
import com.zhu.location.R;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.common.Log;
import com.zhu.salesmanagement.common.MyLocation;
import com.zhu.salesmanagement.common.MyLocation.LocationResult;
import com.zhu.salesmanagement.models.MapFieldVO;
import com.zhu.salesmanagement.overlays.StadiumOverlay;
import com.zhu.salesmanagement.overlays.StadiumOverlayItem;

public class VisitMapActivity extends MapActivity  {
	
    public final static int TYPE_EXACT_POS = 1;
    public final static int TYPE_NEAR_POS = 2;
	public final static int LOGIN_REQUEST_CODE = 10000;
	
	public final static int MAP_ZOOM_LEVEL = 15 ;
	
	private MapView mapView ;
	private MapController mapController ;
	
	public static boolean firstCreatedMapActivity = true ;
	
	private View popView = null ;
	private ImageView myPlaceView = null;
	private Handler hander = new Handler();
	private AsyncTask<Double, Integer, ArrayList<MapFieldVO>> task ;
	
	//private MyLocation mylocation = new MyLocation();
    private Location myCurlocation=null;
    private double lng ;
	private double lat ; 
	private int typeid=-1;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_map);
        setupViews();
        initMapData();
    }

    private void setupViews() {
        lng=this.getIntent().getDoubleExtra("LNG", 0);
        lat=this.getIntent().getDoubleExtra("LAT", 0);
        typeid=this.getIntent().getIntExtra("ID", -1);
        this.mapView = (MapView) this.findViewById(R.id.map_view);

    	myPlaceView=(ImageView)this.findViewById(R.id.myplaceImage);
    	myPlaceView.setImageResource(R.drawable.myplace);
    	myPlaceView.setOnClickListener(new ImageView.OnClickListener(){
			public void onClick(View v) {
				goMyplace();
			}	
    	 }
    	);

    	
    	((Button) findViewById(R.id.left_button)).setOnClickListener(buttonClickListener);
    	//可以多点触摸放大
        //mapView.setSatellite(true);//使用卫星图
        //GeoPoint point=new GeoPoint(39000000, 116000000);
        this.mapController=mapView.getController();
        this.mapController.setZoom(MAP_ZOOM_LEVEL);
        // 设置启用内置的缩放控件
        mapView.setBuiltInZoomControls(true);
        
        if(typeid== TYPE_NEAR_POS){
        	setupMyLocationInfo(lat,lng);
        }else{
            android.util.Log.e("zhu",lng + ","+lat);
        	GeoPoint currentGeo = new GeoPoint((int) (lat * 1e6),(int) (lng * 1e6));
	        VisitMapActivity.this.mapController.animateTo(currentGeo);//通过动画方式移动到指定坐标
        	ArrayList<MapFieldVO> temdata =new ArrayList<MapFieldVO>();
        	MapFieldVO tem = new MapFieldVO();
        	tem.lat = lat;
        	tem.lng = lng;
        	tem.field_addr = this.getIntent().getStringExtra("ADDR");
        	tem.field_name = this.getIntent().getStringExtra("NAME");
        	tem.field_desc = this.getIntent().getStringExtra("DESC");
        	temdata.add(tem);
        	updateOverlays(temdata);
        }
    }
    
    private OnClickListener buttonClickListener = new OnClickListener() {
		
		
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.left_button:
					finish();
					break;
				default:
					break;
			}
		}
	};
    
    /**
     * init map data
     */
    private void initMapData(){
        boolean isGPSOK = Actions.isGPSWorking(this);
        if (firstCreatedMapActivity && !isGPSOK) {
			Actions.alertShowDetails(this, getResources().getString(R.string.notice), getResources().getString(R.string.noticeGPS), 
					R.string.dialog_setting , R.string.dialog_network_location,
					new android.content.DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface arg0, int arg1) {
							Actions.openSettingIntent(VisitMapActivity.this, Settings.ACTION_LOCATION_SOURCE_SETTINGS);
						}
					} ,
					new android.content.DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface arg0, int arg1) {
							 //mylocation.getLocation(VisitMapActivity.this, locationResult);
						}
					}
			);
			
			firstCreatedMapActivity = false ;
			
		} else {
			//mylocation.getLocation(this, locationResult);
		}
    }
    
    public LocationResult locationResult = new LocationResult(){
        
        public void gotLocation(final Location location){
            //Got the location!
        	if(location != null) {
        		myCurlocation=location;
//    			setupMyLocationInfo(location);
//    			getAddressbyGeoPoint(Three61MapActivity.this,location);
    		}
        }
    };
    	
    /**
     * @param data
     */
    private void updateOverlays(ArrayList<MapFieldVO> data) {
    	if (data != null && data.size() > 0) {
	        List<Overlay> overlays = this.mapView.getOverlays();
	        /*
	        Drawable currentDefaultMaker = getResources().getDrawable(R.drawable.ic_maps_indicator_current_position) ;
	        CurrentPositionOverlay currentPostionOverlays = new CurrentPositionOverlay(currentDefaultMaker,this,null);
	        OverlayItem currentItem = new OverlayItem(currentGeo, "You are Here", "Welcome to HoopChina.com");
	        currentPostionOverlays.addOverlay(currentItem);
	        overlays.add(currentPostionOverlays);
	        */
	        Drawable stadiumDrawable = getResources().getDrawable(R.drawable.db_r) ;
	        StadiumOverlay stadiumOverlay = new StadiumOverlay(stadiumDrawable, this, null);
	        for (int i = 0; i < data.size(); i++) {
	        	MapFieldVO dataItem = data.get(i);
	        	if (dataItem != null) {
	        		StadiumOverlayItem item = new StadiumOverlayItem(dataItem);
	        		stadiumOverlay.addOverlay(item);
				}
			}
	        //stadiumOverlay.setOnFocusChangeListener(onPopChangeListener);
	        //overlays.add(stadiumOverlay);
    	}
    	this.getWindow().getDecorView().invalidate();
    }

	
	protected boolean isLocationDisplayed() {
		return super.isLocationDisplayed();
	}

	
	protected boolean isRouteDisplayed() {
		return false;
	}

	
	protected void onDestroy() {
		super.onDestroy();
//		if (task != null && task.getStatus() == AsyncTask.Status.RUNNING) 
//        {
//			task.cancel(true);
//        }
	}

	
	public void onNewIntent(Intent arg0) {
		super.onNewIntent(arg0);
	}

	
    protected void onStart() {
    	super.onStart();
    }
    	
	
	protected void onPause() {
		super.onPause();
		//locationManager.removeUpdates(locationListener);
	}

	
	protected void onResume() {
		super.onResume();
		//locationManager.requestLocationUpdates(bestProvider, 20000, 1, locationListener);
		//mylocation.getLocation(this, locationResult);
	}

	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case LOGIN_REQUEST_CODE:
				
				break;
	
			default:
				break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	private void setupMyLocationInfo(final Location loc){
		hander.post(new Runnable() {
			public void run() {
				if (loc != null) {
					GeoPoint currentGeo = new GeoPoint((int) (loc.getLatitude() * 1e6),(int) (loc.getLongitude() * 1e6));
			        VisitMapActivity.this.mapController.animateTo(currentGeo);//通过动画方式移动到指定坐标
//			        if (task != null && task.getStatus() == AsyncTask.Status.RUNNING) {
//						task.cancel(true);
//			        }
			        //task = new FetchMapFieldDataTask().execute(loc.getLatitude() , loc.getLongitude());
				}
			}
		});
		
	}
	
	private void setupMyLocationInfo(final double latitude,final double longitude ){
		hander.post(new Runnable() {
			
			public void run() {
					GeoPoint currentGeo = new GeoPoint((int) (latitude * 1e6),(int) (longitude * 1e6));
			        VisitMapActivity.this.mapController.animateTo(currentGeo);//通过动画方式移动到指定坐标
//			        if (task != null && task.getStatus() == AsyncTask.Status.RUNNING) {
//						task.cancel(true);
//			        }
			       // task = new FetchMapFieldDataTask().execute(latitude , longitude);
				}
		});
		
	}
	  
//	 private OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
//	    	
//	    	public void onFocusChanged(ItemizedOverlay overlay, OverlayItem newFocus) {
//	    		//DialogUtil.getSimpleDialog(context, newFocus.getTitle(), newFocus.getSnippet()).show();
//	    		//jump2DetailsActivity();
//	    	}
//		};
	
		/** 
	     * 气泡窗口监听器 
	     */  
	 private final ItemizedOverlay.OnFocusChangeListener onPopChangeListener = new ItemizedOverlay.OnFocusChangeListener() {  
          
        public void onFocusChanged(ItemizedOverlay overlay, OverlayItem newFocus) {  
            // 创建气泡窗口  
            if (popView != null) {  
                popView.setVisibility(View.GONE);  
            }  
            if (newFocus != null) {  
            	
            	VisitMapActivity.this.mapController.animateTo(newFocus.getPoint());
            	
                MapView.LayoutParams geoLP = (MapView.LayoutParams) popView.getLayoutParams();  
                geoLP.point = newFocus.getPoint();// 这行用于popView的定位  
                
                LinearLayout popView_layout = (LinearLayout) popView.findViewById(R.id.popview_layout);
                popView_layout.setOnClickListener(popViewClickListener);
                /*
                ImageButton check_details = (ImageButton) popView.findViewById(R.id.check_details_btn);
                check_details.setOnClickListener(popViewClickListener);
                */
                popView_layout.setTag (((StadiumOverlayItem)newFocus).getData().field_id );
                
                TextView title = (TextView) popView.findViewById(R.id.overlay_field_title_txt);  
                title.setText(newFocus.getTitle());  
                
                
                TextView desc = (TextView) popView.findViewById(R.id.overlay_field_disc_txt);
                if (newFocus.getSnippet() == null || newFocus.getSnippet().length() == 0) {  
                    desc.setVisibility(View.GONE);  
                } else {  
                    desc.setVisibility(View.VISIBLE);  
                    desc.setText(newFocus.getSnippet());  
                }  
                mapView.updateViewLayout(popView, geoLP);  
                popView.setVisibility(View.VISIBLE);  
            }  
        }  
    };  	
    
    private OnClickListener popViewClickListener = new OnClickListener() {
		
		public void onClick(View v) {
			long field_id = Long.valueOf(String.valueOf(v.getTag()));
			if (field_id > 0 ) {
				jump2DetailsActivity(field_id);
			}
		}
	};
	
	private void jump2DetailsActivity(long value) {
//		Intent tent = new Intent(this, MapNoteDetailsActivity.class);
//		tent.putExtra("field_id", value);
//		startActivity(tent);
	}
	
	/**
	 * FetchMapFieldDataTask
	 * @author shane
	 *
	 */
//	public class FetchMapFieldDataTask extends AsyncTask<Double, Integer, ArrayList<MapFieldVO>> {
//		
//		protected void onPreExecute() {
//			super.onPreExecute();
//				showDialog(FETCH_MAP_DATA_DIALOG);
//		}
//		
//		protected ArrayList<MapFieldVO> doInBackground(Double... params) {
//			return null;//Three61MapAPI.getFieldsByPoint(params[0], params[1], 5000);
//		}
//		
//		
//		protected void onPostExecute(ArrayList<MapFieldVO> result) {
//			super.onPostExecute(result);
//			dismissDialog(FETCH_MAP_DATA_DIALOG);
//			
//			updateOverlays(result);
////			DataCenter.self().mapData = result ;
//		}
//	}
	
	public final static int FETCH_MAP_DATA_DIALOG = 2001;
	
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case FETCH_MAP_DATA_DIALOG:
				ProgressDialog pd = new ProgressDialog(this);
				pd.setMessage(this.getString(R.string.load_map_data));
				return pd ;
			default:
				break;
		}
		return super.onCreateDialog(id);
	}
	
	
//	public void onBackPressed() {
//		Actions.alertShowDetails(this, getString(R.string.tips_label), getString(R.string.do_quit_app), 
//				R.string.dialog_yes, R.string.dialog_no, 
//				new android.content.DialogInterface.OnClickListener() {
//					
//					
//					public void onClick(DialogInterface arg0, int arg1) {
//						Three61MapActivity.this.finish();
//					}
//				}, 
//				new android.content.DialogInterface.OnClickListener() {
//					
//					
//					public void onClick(DialogInterface arg0, int arg1) {
//						
//					}
//				});
//	}
	
    //通过GeoPoint来获取Address  
    public  Address getAddressbyGeoPoint(Context cntext, Location location) {  
        Address result = null;  
        try {  
        	Log.e("getAddressbyGeoPoint");
            if (location != null) {  
                Geocoder gc = new Geocoder(cntext, Locale.getDefault ()/*Locale.CHINA*/);  
                List<Address> lstAddress = gc.getFromLocation(location.getLatitude(),  
                		location.getLongitude(), 1);  
                if (lstAddress.size() > 0) {  
                    result = lstAddress.get(0);  
                }  
                Actions.toastShort(VisitMapActivity.this, result.getAdminArea()+result.getCountryName()+result.getCountryCode()+result.getLocality());
                Log.e("location != null");
            }  
        } catch (Exception e) { 
        	Log.e("Exception");
            e.printStackTrace();  
        }  
        return result;  
    }  
    
    private void goMyplace(){
    	setupMyLocationInfo(myCurlocation);
    	Log.e("goMyplace");
    	Log.e("myCurlocation="+myCurlocation);
    }
}